package alogrithm;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/11/18 12:08
 */
public class FindTilt {
    private int ans = 0;

    public int findTilt(TreeNode root) {
        if (root == null) {
            return 0;
        }
        dfs(root);
        return ans;
    }

    private int dfs(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int sum1 = dfs(node.left);
        int sum2 = dfs(node.right);
        ans += Math.abs(sum1 - sum2);
        return sum1 + sum2 + node.val;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
